import os
import subprocess

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QGridLayout, QMessageBox, QLabel, QComboBox, QVBoxLayout, QFrame


class BrowserIncognito(QWidget):

    def delete_file(self):
        dlg = QMessageBox()
        dlg.setWindowTitle('Внимание')
        if os.path.isfile(self.override_filename):
            os.remove(self.override_filename)
            dlg.setText('Файл удалён.')
        else:
            dlg.setText('Файл не существует.')
        dlg.exec()
        self.reload_labels()

    def restore_file(self):
        if os.path.isfile(self.override_filename):
            os.remove(self.override_filename)
        export_flags = 'CHROMIUM_USER_FLAGS' if self.browser_name == 'Chromium' else 'YANDEX_BROWSER_FLAGS'
        text = f"""#!/bin/sh
# Different people use interactive panels,
# protect them from accidental leaks of logins etc.
export {export_flags}="--incognito\""""
        with open(self.override_filename, 'w') as out:
            out.write(text)
        dlg = QMessageBox()
        dlg.setWindowTitle('Внимание')
        dlg.setText('Файл восстановлен из исходных настроек.')
        dlg.exec()
        self.reload_labels()

    def edit_file(self):
        if not os.path.isfile(self.override_filename):
            subprocess.run(f'touch {self.override_filename}', shell=True)
        subprocess.run(f'kate {self.override_filename}', shell=True)
        self.reload_labels()

    def turn_incognito_on(self, turn_on=True):
        export_flags = 'CHROMIUM_USER_FLAGS' if self.browser_name == 'Chromium' else 'YANDEX_BROWSER_FLAGS'
        if not os.path.isfile(self.override_filename):
            subprocess.run(f'touch {self.override_filename}', shell=True)
        lines = open(self.override_filename, 'r').readlines()
        for i in range(len(lines)):
            if lines[i].startswith('export') and export_flags in lines[i]:
                current_flags = lines[i].split('=')[-1].strip().strip('"').split()
                if turn_on and '--incognito' not in current_flags:
                    current_flags.append('--incognito')
                elif not turn_on and '--incognito' in current_flags:
                    current_flags.remove('--incognito')
                lines[i] = lines[i].split('=')[0] + '="' + ' '.join(current_flags) + '"' if current_flags else ''
                break
        else:
            if turn_on:
                lines.append(f'export {export_flags}="--incognito"')
        with open(self.override_filename, 'w') as out:
            out.write(''.join(lines))
        dlg = QMessageBox()
        dlg.setWindowTitle('Внимание')
        dlg.setText(f'Режим инкогнито для {self.browser_name} в{"ы" if not turn_on else ""}ключен.')
        dlg.exec()
        self.reload_labels()

    def reload_labels(self):
        if os.path.isfile(self.filename):
            self.default_settings_label.setText(''.join(open(self.filename).readlines()))
        else:
            self.default_settings_label.setText('Не найдено')
        if os.path.isfile(self.override_filename):
            self.override_settings_label.setText(''.join(open(self.override_filename).readlines()))
        else:
            self.override_settings_label.setText('Не найдено')

    def __init__(self,
                 filename='',
                 override_filename='',
                 browser_name=''):
        super().__init__()
        self.filename = filename
        self.override_filename = override_filename
        self.browser_name = browser_name

        central_widget_layout = QGridLayout()
        self.setLayout(central_widget_layout)

        switch_chromium_mode = QLabel(f'Переключение режимов в {browser_name}')
        switch_chromium_mode.setAlignment(Qt.AlignCenter)
        central_widget_layout.addWidget(switch_chromium_mode, 0, 0, 1, 2)

        label_current_header = QLabel('Исходные настройки:')
        label_current_header.setAlignment(Qt.AlignRight | Qt.AlignTop)
        central_widget_layout.addWidget(label_current_header, 1, 0)
        label_override_header = QLabel('Перезаписанные настройки:')
        label_override_header.setAlignment(Qt.AlignRight | Qt.AlignTop)
        central_widget_layout.addWidget(label_override_header, 2, 0)
        self.default_settings_label = QLabel()
        self.default_settings_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.override_settings_label = QLabel()
        self.override_settings_label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.reload_labels()
        central_widget_layout.addWidget(self.default_settings_label, 1, 1)
        central_widget_layout.addWidget(self.override_settings_label, 2, 1)
        action_label = QLabel('Действие')
        action_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.action_list = QComboBox()
        self.action_list.addItems(['Без изменений', 'Удалить файл', 'Восстановить файл', 'Редактировать файл',
                                   'Включить режим инкогнито', 'Выключить режим инкогнито'])
        central_widget_layout.addWidget(action_label, 3, 0)
        central_widget_layout.addWidget(self.action_list, 3, 1)

        central_widget_layout.addWidget(QLabel(''), 4, 0)
        central_widget_layout.setRowStretch(0, 0)
        central_widget_layout.setRowStretch(1, 0)
        central_widget_layout.setRowStretch(2, 0)
        central_widget_layout.setRowStretch(3, 0)
        central_widget_layout.setRowStretch(4, 1)


class AllBrowsersIncognito(QWidget):

    def __init__(self):
        super().__init__()

        layout = QVBoxLayout(self)
        self.setLayout(layout)
        self.chromium_widget = BrowserIncognito(
            filename='/etc/profile.d/10-chromium-default-incognito.sh',
            override_filename='/etc/profile.d/11-chromium-default-incognito.sh',
            browser_name='Chromium'
        )
        layout.addWidget(self.chromium_widget)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setLineWidth(1)
        layout.addWidget(line)
        self.yandex_browser_widget = BrowserIncognito(
            filename='/etc/profile.d/10-yandex-default-incognito.sh',
            override_filename='/etc/profile.d/11-yandex-default-incognito.sh',
            browser_name='Яндекс Браузер'
        )
        layout.addWidget(self.yandex_browser_widget)
        
    def browsers_action(self):
        for widget in (self.chromium_widget, self.yandex_browser_widget):
            if widget.action_list.currentIndex() == 1:
                widget.delete_file()
            elif widget.action_list.currentIndex() == 2:
                widget.restore_file()
            elif widget.action_list.currentIndex() == 3:
                widget.edit_file()
            elif widget.action_list.currentIndex() == 4:
                widget.turn_incognito_on(True)
            elif widget.action_list.currentIndex() == 5:
                widget.turn_incognito_on(False)

